package com.yizhuoyan.his.serviceimpl.doctor.outpatient;

import com.yizhuoyan.his.ao.DisposalRecordAo;
import com.yizhuoyan.his.dao.CaseCheckRecordDao;
import com.yizhuoyan.his.dao.CaseMedicalRecordDao;
import com.yizhuoyan.his.dao.CaseRegistrationRecordDao;
import com.yizhuoyan.his.dao.HosDoctorDao;
import com.yizhuoyan.his.entity.CaseCheckRecordEntity;
import com.yizhuoyan.his.entity.HosDoctorEntity;
import com.yizhuoyan.his.exception.HISDataNotExistsException;
import com.yizhuoyan.his.exception.HISException;
import com.yizhuoyan.his.exception.HISIllegalParameterException;
import com.yizhuoyan.his.service.doctor.outpatient.DisposalApplyService;
import com.yizhuoyan.his.servicesupport.DatabaseIdGenerateSupportService;
import com.yizhuoyan.his.util.BeanMap;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.validation.Valid;
import java.time.LocalDateTime;

/**
 * 处置申请服务
 * author：ZJH
 */
@Service
@Transactional
@Validated
@Slf4j
public class DisposalApplyServiceImpl implements DisposalApplyService {

    @Autowired
    CaseCheckRecordDao caseCheckRecordDao;
    @Autowired
    HosDoctorDao hosDoctorDao;
    @Autowired
    CaseMedicalRecordDao caseMedicalRecordDao;
    @Autowired
    CaseRegistrationRecordDao caseRegistrationRecordDao;
    @Autowired
    DatabaseIdGenerateSupportService idGenerateSupportService;

    @Override
    public void addDisposalRecordTemporary(@NonNull @Valid DisposalRecordAo ao) throws Exception {
        log.trace("暂存处置申请,验证参数：{}", ao);
        checkDisposalRecordAo(ao);
        //项目id们
        String[] nodrugExpenseItemIds = ao.getNodrugExpenseItemId();
        //项目名称们
        String[] projectName = ao.getProjectName();
        //病例id
        long medicalRecordId = Long.parseLong(ao.getMedicalRecordId());
        //挂号id
        long registrationRecordId = Long.parseLong(ao.getRegistrationRecordId());
        //是否加急  1为加急 0为不加急
        Integer urgent = ao.getUrgent() == null ? 0 : Integer.parseInt(ao.getUrgent());

        for (int i = 0; i < nodrugExpenseItemIds.length; i++) {
            CaseCheckRecordEntity entity = new CaseCheckRecordEntity();
            entity.setId(idGenerateSupportService.nextId());
            entity.setCreateTime(LocalDateTime.now());
            entity.setMedicalRecordId(medicalRecordId);
            entity.setRegistrationRecordId(registrationRecordId);
            entity.setNodrugExpenseItemId(Long.parseLong(nodrugExpenseItemIds[i]));
            entity.setProjectName(projectName[i]);
            entity.setObjective(ao.getObjective());
            entity.setPosition(ao.getPosition());
            entity.setUrgent(urgent);
            entity.setState(1);
            entity.setRecordType(3);
            caseCheckRecordDao.insert(entity);
        }

    }

    @Override
    public void addDisposalRecordOpen(Long doctorId, @NonNull @Valid DisposalRecordAo ao) throws Exception {
        log.trace("暂存处置申请,验证参数：{}和{}", doctorId, ao);
        checkDisposalRecordAo(ao);
        checkId(doctorId, "开立医生id");
        log.trace("验证开立医生id:{}是否存在", doctorId);
        HosDoctorEntity hosDoctorEntity = hosDoctorDao.selectById(doctorId);
        if (hosDoctorEntity == null) {
            throw new HISDataNotExistsException("此开立医生不存在");
        }

        //项目id们
        String[] nodrugExpenseItemIds = ao.getNodrugExpenseItemId();
        //项目名称们
        String[] projectName = ao.getProjectName();
        //病例id
        long medicalRecordId = Long.parseLong(ao.getMedicalRecordId());
        //挂号id
        long registrationRecordId = Long.parseLong(ao.getRegistrationRecordId());
        //是否加急  1为加急 0为不加急
        Integer urgent = ao.getUrgent() == null ? 0 : Integer.parseInt(ao.getUrgent());

        for (int i = 0; i < nodrugExpenseItemIds.length; i++) {
            CaseCheckRecordEntity entity = new CaseCheckRecordEntity();
            entity.setId(idGenerateSupportService.nextId());
            entity.setMedicalRecordId(medicalRecordId);
            entity.setCreateDoctorId(doctorId);
            entity.setCreateTime(LocalDateTime.now());
            entity.setRegistrationRecordId(registrationRecordId);
            entity.setNodrugExpenseItemId(Long.parseLong(nodrugExpenseItemIds[i]));
            entity.setProjectName(projectName[i]);
            entity.setObjective(ao.getObjective());
            entity.setPosition(ao.getPosition());
            entity.setUrgent(urgent);
            entity.setState(2);
            entity.setRecordType(3);
            caseCheckRecordDao.insert(entity);
        }
    }

    @Override
    public void removeDisposalRecord(Long id) throws Exception {
        checkId(id, "处置申请id");
        log.trace("验证处置申请id:{}是否存在", id);
        CaseCheckRecordEntity entity = caseCheckRecordDao.selectById(id);
        if (entity == null) {
            throw new HISDataNotExistsException("此处置申请不存在");
        }
        Integer state = entity.getState();
        if (state != 1 && state != 0) {
            throw new HISException("RemoveFail", "选中的项目不能删除");
        }

        caseCheckRecordDao.delete(id);
    }

    @Override
    public void nullifyDisposalRecord(Long id) throws Exception {
        checkId(id, "处置申请id");
        log.trace("验证处置申请id:{}是否存在", id);
        CaseCheckRecordEntity entity = caseCheckRecordDao.selectById(id);
        if (entity == null) {
            throw new HISDataNotExistsException("此处置申请不存在");
        }
        Integer state = entity.getState();
        if (state != 1) {
            throw new HISException("NullifyFail", "选中的项目不能作废");
        }

        caseCheckRecordDao.update(id, BeanMap.ofOnly("state", 0));
    }

    /**
     * 验证处置申请参数
     *
     * @param ao
     * @throws Exception
     */
    private void checkDisposalRecordAo(DisposalRecordAo ao) throws Exception {

        log.trace("判断挂号id是否存在");
        long registrationRecordId = Long.parseLong(ao.getRegistrationRecordId());
        if (caseRegistrationRecordDao.selectById(registrationRecordId) == null) {
            log.trace("挂号id:{}不存在", registrationRecordId);
            throw new HISDataNotExistsException("挂号id不存在");
        }
        ;
        log.trace("判断病例id是否存在");
        long medicalRecordId = Long.parseLong(ao.getMedicalRecordId());
        if (caseMedicalRecordDao.selectById(medicalRecordId) == null) {
            log.trace("病历id:{}不存在", medicalRecordId);
            throw new HISDataNotExistsException("病历id不存在");
        }
        ;

        //验证项目id
        log.trace("判断验证项目id是否合法");
        String[] nodrugExpenseItemId = ao.getNodrugExpenseItemId();
        long itemId;
        if (nodrugExpenseItemId == null || nodrugExpenseItemId.length == 0) {
            throw new NullPointerException("未选择项目！");
        } else {
            for (int i = 0; i < nodrugExpenseItemId.length; i++) {
                try {
                    itemId = Long.parseLong(nodrugExpenseItemId[i]);
                    checkId(itemId, "项目id");
                } catch (NumberFormatException e) {
                    throw new HISIllegalParameterException("项目id有误！");
                }
            }
        }
        log.trace("验证项目名是否为空");
        String[] projectName = ao.getProjectName();
        if (projectName == null || projectName.length == 0) {
            throw new NullPointerException("未选择项目！");
        }
    }

    /**
     * 判断id是否合法
     *
     * @param id
     * @param idName
     */
    private void checkId(@NonNull Long id, String idName) {
        log.trace("判断id是否合法");
        if (id < 0) {
            throw new HISIllegalParameterException("参数" + idName + ":不合法");
        }
    }
}
